#include "stdafx.h"
#include "DirectoryExplorer.h"
#include <iostream>

DirectoryExplorer::DirectoryExplorer(std::string& pathToDir)
{
	using namespace boost::filesystem3;

	endIter = new directory_iterator();

	path dirPath(pathToDir);	
	dirPathStack = new std::stack<directory_iterator*>(); 
	dirPathStack->push(new directory_iterator(dirPath));
}

DirectoryExplorer::~DirectoryExplorer()
{
	delete(endIter);
	delete(dirPathStack);
}

std::string DirectoryExplorer::getNextFile()
{
	using namespace boost::filesystem3;
	
	directory_iterator* workIter;

	while (!(dirPathStack->empty()))
	{
		workIter = dirPathStack->top();
		if ((*workIter) == (*endIter))
		{
			delete(workIter);
			dirPathStack->pop();			
			continue;
		}

		if (is_directory((*workIter)->path()))
		{
			try 
			{
				dirPathStack->push(new directory_iterator((*workIter)->path()));
			}
			catch(boost::filesystem::filesystem_error& ex)
			{
				// do nothing, just go to the next item
			}
			(*workIter)++;
			continue;
		}

		std::string resPath = (*workIter)->path().string();
		(*workIter)++;
		return resPath;
	}
	return "";
}